#define vs. const variable

您所在的位置:网站首页 arduino const int #define vs. const variable

#define vs. const variable

##define vs. const variable| 来源: 网络整理| 查看: 265

DJ,

The #define pre-dates const declarations. Since #define just causes a string substitution, just as if you got in an editor and said:

Replace all instances of LEDPIN with 3

This replacement is done by the pre-processor, and all happens before the compiler ever looks at your code. In other words, the compiler never sees "LEDPIN". It only sees "3".

The advantage to using #define is that you can do some tricky things with strings. For example, you can assemble a string out of several #define definitions.

You can also create code with a #define:

#define FOREVER for( ; ; ) FOREVER  {  if (serial.available() > 0)    ...  }

You can also have a #define that takes arguments and substitutes those arguments into its output.

The disadvantage to #define is that since the compiler doesn't see your original code, it doesn't have any idea what you're trying to do. This is where const shines.

The compiler handles const declarations. It knows, and equally importantly, someone reading your program knows, the type of constant you're declaring.

My rule is to use const wherever I can, and use #define everywhere else. Whichever you use, you can eliminate "magic numbers" so that you never leave someone reading your code wondering what you are trying to do. Would you rather read this:get_sensor_value(3.25);

or this:

const float sensor_calibration = 3.25;    // determined by experimenting get_sensor_value(sensor_calibration);

Regards,

-Mike



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3